package org.hdl.anima.message;

import java.io.IOException;

import org.hdl.anima.common.io.InputArchive;
import org.hdl.anima.common.io.OutputArchive;

/**
 * 
 * @author qiuhd
 * @since  2014-2-17
 * @version V1.0.0
 */
public abstract class Response implements IResponse{
	
	public static final int OK = 200 ;
	
	public static final int BAD = 404 ;
	
	private IRequest request ;
	
	private int id;
	
	private boolean encrypted = false;
	/**
	 * 消息序列
	 */
	private int seq ;
	/**
	 * 错误码
	 */
	private int errorCode;
	
	private String errorDes;
	
	public Response() {
		this(OK);
	}
	
	public Response(int errorCode) {
		this(OK,null);
	}
	
	public Response(int errorCode,String errorDes) {
		this.errorCode = errorCode;
		this.errorDes = errorDes;
	}

	@Override
	public void serialize(OutputArchive archive) throws IOException {
		archive.writeInt(this.id);
		archive.writeInt(seq);
		archive.writeInt(errorCode);
		archive.writeString(errorDes);
		if(errorCode == OK) {
			doSerialize(archive);
		}
	}

	@Override
	public void deserialize(InputArchive archive) throws IOException {
		this.seq = archive.readInt();
		this.errorCode = archive.readInt();
		this.errorDes = archive.readString();
		if(errorCode == OK) {
			doDeserialize(archive);
		}
	}
	
	@Override
	public void display(StringBuilder builder, int level) {
		MDisplayer displayer = new MDisplayer(builder);
		displayer.display(this.id, "id");
		displayer.display(this.request != null ? this.request.getSeq():null, "seq");
		displayer.display(errorCode, "errorCode");
		displayer.display(errorDes, "errorDes");
		doDisplay(displayer);
	}

	@Override
	public void displaySimple(StringBuilder builder, int level) {
		
	}

	public abstract void doSerialize(OutputArchive out) throws IOException;
	
	public abstract void doDeserialize(InputArchive in) throws IOException;

	public abstract void doDisplay(MDisplayer displayer) ;
	
	public abstract void displaySimple(MDisplayer displayer) ;

	public void setRequest(IRequest request) {
		this.request = request;
		this.id = request.getId();
		this.seq = request.getSeq();
	}

	@Override
	public IRequest getRequest() {
		return this.request;
	}

	@Override
	public void setErrorDes(String errorDes) {
		this.errorDes = errorDes;
	}

	@Override
	public String getErrorDes() {
		return this.errorDes;
	}

	@Override
	public void setErrorCode(int error) {
		this.errorCode = error;
	}

	@Override
	public int getErrorCode() {
		return this.errorCode;
	}

	@Override
	public void setId(int id) {
		this.id = id;
	}

	@Override
	public int getId() {
		return this.id;
	}
	
	@Override
	public boolean isEncrypted() {
		return this.encrypted;
	}

	@Override
	public void setEncrypted(boolean encrypted) {
		this.encrypted = encrypted;
	}

	public int getSeq() {
		return seq;
	}
}

